<template>
  <div class="tinymce-boxeditor">
    <editor
      :id="id"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick"/>
  </div>
</template>
<script>
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver'

// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import 'tinymce/plugins/table'// 插入表格插件
import 'tinymce/plugins/lists'// 列表插件
import 'tinymce/plugins/wordcount'// 字数统计插件
import 'tinymce/plugins/paste'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/image'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/print'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/hr'
import '@/tinymce/plugins/formtext'
import '@/tinymce/plugins/formdate'

export default {
  components: {
    Editor
  },
  props: {
    id: {
      type: String,
      default: 'tinymce-' + Date.parse(new Date())
    },
    value: {
      type: String,
      default: ''
    },
    width: {
      type: [String, Number],
      default: '100%'
    },
    height: {
      type: [String, Number],
      default: '500'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    plugins: {
      type: [String, Array],
      default: 'formtext formdate link print preview searchreplace fullscreen lists table wordcount insertdatetime hr code image paste'
    },
    toolbar: {
      type: [String, Array],
      default: 'fullscreen code print preview undo redo | forecolor backcolor bold italic underline strikethrough | bullist numlist |alignleft aligncenter alignright alignjustify outdent indent | styleselect fontselect fontsizeselect | table insertdatetime hr'
    }
  },
  data() {
    return {
      init: {
        selector: '#' + this.id,
        language_url: process.env.BASE_ACCESS_URL + '/static/tinymce/langs/zh_CN.js', // static目录下
        language: 'zh_CN',
        skin_url: process.env.BASE_ACCESS_URL + '/static/tinymce/skins/ui/oxide',
        content_css: process.env.BASE_ACCESS_URL + '/static/tinymce/skins/content/default/content.css',
        height: this.height,
        width: this.width,
        plugins: this.plugins, // 父组件传入 或者 填写个默认的插件 要选用什么插件都可以 去官网可以查到
        toolbar: this.toolbar, // 工具栏 我用到的也就是lists image media table wordcount 这些 根据需求而定
        images_upload_url: '', // 上传路径
        // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        images_upload_handler: async(blobInfo, success, failure) => {
          // new FormData()
          const img = 'data:image/jpeg;base64,' + blobInfo.base64()
          success(img)
        },
        setup: function(editor) {
          console.log('ID为: ' + editor.id + ' 的编辑器即将初始化.')
        },
        init_instance_callback: function(editor) {
          console.log('ID为: ' + editor.id + ' 的编辑器已初始化完成.')
        },
        branding: false, // 技术支持(Powered by Tiny || 由Tiny驱动)
        // menubar: true, // 菜单栏
        menubar: 'file form edit insert view format table tools help',
        menu: {
          form: { title: '表单控件', items: 'formtext-add formdate-add' }
        },
        contextmenu: 'formtext formdate',
        theme: 'silver', // 主题
        min_height: 400,
        sandbox: 'allow-modals allow-forms allow-popups allow-scripts allow-same-origin',
        paste_data_images: true,
        auto_focus: true,
        allow_script_urls: true,
        nowrap: true,
        extended_valid_elements: 'script[src|async|defer|type|charset]',
        fontsize_formats: '10px 12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;'
      },
      myValue: this.value,
      fieldVOList: []
    }
  },
  watch: {
    value(newValue) {
      this.myValue = newValue
    },
    myValue(newValue) {
      this.$emit('input', newValue)
    },
    fieldVOList(newValue) {
      this.setAllElement(this.fieldVOList)
    }
  },
  mounted() {
    tinymce.init({})
  },
  methods: {
    calcWidth() {
      return (document.body.clientWidth - 50) + 'px'
    },
    setAllElement(fieldVOList) {
      const _this = this
      if (!tinymce.activeEditor.plugins.formtext) {
        setTimeout(function() {
          _this.setElement(_this.fieldVOList)
        }, 2000)
        return
      }
      _this.setElement(_this.fieldVOList)
    },
    setElement(fieldVOList) {
      console.log('setelemen begin')
      console.log(fieldVOList)
      const textElement = []
      const dateElement = []
      fieldVOList.forEach((fieldVO) => {
        if (fieldVO.fieldType === 'text') {
          textElement[fieldVO.fieldControlId] = JSON.parse(fieldVO.rmk)
        } else if (fieldVO.fieldType === 'date') {
          dateElement[fieldVO.fieldControlId] = JSON.parse(fieldVO.rmk)
        }
      })
      tinymce.activeEditor.plugins.formtext.setAllElement(textElement)
      tinymce.activeEditor.plugins.formdate.setAllElement(dateElement)
    },
    getAllFormElement() {
      console.log(tinymce.activeEditor.plugins.formtext.getAllElement())
      console.log(tinymce.activeEditor.plugins.formdate.getAllElement())
      const allFormElements = []
      // 文本控件
      const textElements = tinymce.activeEditor.plugins.formtext.getAllElement()
      for (var textId in textElements) {
        const fromData = textElements[textId]
        const tmpData = {}
        tmpData.fieldType = 'text'
        tmpData.fieldControlId = fromData.id
        tmpData.fieldName = fromData.title
        tmpData.fieldDefaultValue = fromData.value
        tmpData.requireFlag = fromData.requireFlag ? 'Y' : 'N'
        tmpData.rmk = fromData
        allFormElements.push(tmpData)
      }
      // 日期控件
      const dateElements = tinymce.activeEditor.plugins.formdate.getAllElement()
      for (var dateId in dateElements) {
        const fromData = dateElements[dateId]
        const tmpData = {}
        tmpData.fieldType = 'date'
        tmpData.fieldControlId = fromData.id
        tmpData.fieldName = fromData.title
        tmpData.fieldDefaultValue = fromData.value
        tmpData.requireFlag = fromData.requireFlag ? 'Y' : 'N'
        tmpData.rmk = fromData
        allFormElements.push(tmpData)
      }
      console.log(allFormElements)
      return allFormElements
    },
    onClick(e) {
      this.$emit('onClick', e, tinymce)
    }
  }
}
</script>
<style scoped>
  .tox-silver-sink .tox-tinymce-aux {
    z-index: 4000;
  }
</style>
